package com.pphh.demo.metric;

import com.codahale.metrics.*;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Please add description here.
 *
 * @author huangyinhuang
 * @date 11/6/2018
 */
public class MetricsFactory {

    private static final MetricRegistry metrics = new MetricRegistry();
    private static MetricsFactory instance = new MetricsFactory();

    private ConsoleReporter consoleReporter;
    private Slf4jReporter slf4jReporter;
    private JmxReporter jmxReporter;

    private MetricsFactory() {
        this.consoleReporter = ConsoleReporter.forRegistry(metrics)
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();

        this.slf4jReporter = Slf4jReporter.forRegistry(metrics)
                .outputTo(LoggerFactory.getLogger("demo.metrics"))
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();

        this.jmxReporter = JmxReporter.forRegistry(metrics).build();
    }

    public static MetricsFactory getInstance() {
        return instance;
    }

    public Meter getMeter(String name) {
        return metrics.meter(name);
    }

    public Histogram getHistogram(String name) {
        return metrics.histogram(name);
    }

    public Counter getCounter(String name) {
        return metrics.counter(name);
    }

    public Timer getTimer(String name) {
        return metrics.timer(name);
    }

    public QueueManager getQueueManager() {
        return new QueueManager(metrics, "queue");
    }

    public void startReporter() {
        this.consoleReporter.start(5, TimeUnit.SECONDS);
    }

    public void stopReporter() {
        this.consoleReporter.stop();
    }

}
